package com.gitee.hermer.engine.jars.core.utils;

import java.io.File;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

import com.gitee.hermer.boot.jee.commons.encrypt.Md5Utils;
import com.gitee.hermer.boot.jee.commons.exception.ErrorCode;
import com.gitee.hermer.boot.jee.commons.reflect.ClassUtils;
import com.gitee.hermer.boot.jee.commons.utils.FileUtils;
import com.gitee.hermer.boot.jee.commons.utils.StringUtils;
import com.gitee.hermer.boot.jee.commons.verify.Assert;
import com.gitee.hermer.engine.jars.core.domain.EngineConstant;

public final class PropertiesUtils{
	
	
	final static Map<String, Properties> CACHE_MD5 = new ConcurrentHashMap<String, Properties>();
	
	
	public static String getPropertieString(String fileName,String key,String defaultVal){
		return getPropertieValue(fileName, key, defaultVal);
	}
	
	public static Integer getPropertieInteger(String fileName,String key,Integer defaultVal){
		return getPropertieValue(fileName, key, defaultVal);
	}
	
	public static Boolean getPropertieBoolean(String fileName,String key,Boolean defaultVal){
		return getPropertieValue(fileName, key, defaultVal);
	}
	
	public static String getPropertieString(String fileName,String key){
		return getPropertieString(fileName, key, null);
	}
	
	public static Integer getPropertieInteger(String fileName,String key){
		return getPropertieInteger(fileName, key, null);
	}
	
	public static Boolean getPropertieBoolean(String fileName,String key){
		return getPropertieBoolean(fileName, key, null);
	}

	public static <T> T getPropertieValue(String fileName,String key,T defaultVal){
		try{
			String md5 = StringUtils.toHexString(Md5Utils.md5(FileUtils.readBytes(new File(ClassUtils.getContextClassLoader().getResource(fileName).toURI()))));
			if(!CACHE_MD5.containsKey(md5)){
				CACHE_MD5.put(md5, com.gitee.hermer.boot.jee.commons.utils.PropertiesUtils.loadProperties(fileName));
			}
			Properties properties = CACHE_MD5.get(md5);
			Assert.notNullCode(properties,ErrorCode.DATA_ERROR,"没有找到%s文件！",fileName);
			if(defaultVal != null)
				return (T) properties.getOrDefault(key, defaultVal);
			else
				return (T) properties.get(key);
		}catch (Exception e) {
			EngineConstant.LOGGER.error(e.getMessage(),e);
		}
		return null;
	}

}
